package com.tledu.zyf.service.impl;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.tledu.zyf.dao.IAttachmentDao;
import com.tledu.zyf.exception.SSMException;
import com.tledu.zyf.model.Attachment;
import com.tledu.zyf.service.IAttachmentService;

@Service
public class AttachmentService implements IAttachmentService {

	@Autowired
	private IAttachmentDao attachmentDao;

	@Override
	public void add(MultipartFile file, String filepath) throws SSMException {
		InputStream inputStream = null;
		try {
			// 转换为流
			inputStream = file.getInputStream();
			// 判断字节个数,是否为空
			if (inputStream.available() <= 0) {
				throw new SSMException("请选择非空文件 ! ");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 获取文件后缀
		String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
		// 获取文件名
		String oldName = FilenameUtils.getBaseName(file.getOriginalFilename());
		// 新名字
		String newName = System.currentTimeMillis() + oldName + (int) (Math.random() * 10000);
		// 文件大小
		long size = file.getSize();
		// 封装实体类
		Attachment attachment = new Attachment(newName, oldName, size, suffix);

		// 添加到数据库
		attachmentDao.add(attachment);

		// 上传到本地文件
		File dostFile = new File(filepath + "/" + newName + "." + suffix);

		try {
			FileUtils.copyInputStreamToFile(inputStream, dostFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delete(int id, String filepath) {

		// 获取文件信息
		Attachment attachment = attachmentDao.load(id);
		// 删除数据库文件
		attachmentDao.delete(id);
		// 删除本地文件
		filepath += "/" + attachment.getNewName() + "." + attachment.getSuffix();
		File file = new File(filepath);
		// 调用 delete 方法删除文件
		file.delete();
	}

	@Override
	public List<Attachment> list() {
		return attachmentDao.list();
	}

}
